package ihm;

import java.awt.*;
import javax.swing.*;

import static javax.swing.GroupLayout.Alignment.*;
import javax.swing.filechooser.FileFilter;
import javax.swing.plaf.OptionPaneUI;
import javax.xml.bind.annotation.adapters.HexBinaryAdapter;

import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

import execution.CampagneDeTest;
import execution.CasDeTest;
import execution.ExecutionCode;


import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Vector;
import java.util.concurrent.Semaphore;

import execution.CampagneDeTest;
import generation.*;

/**
 * Fenetre d'accueil
 * 
 */
public class Accueil extends JFrame implements ActionListener{

	private JButton parcourir;
	private JButton executer;
	private JButton genererCode;
	private JButton fermer;
	private JTextField textField;
	private JTextArea textArea;
	private JLabel label1;
	private JLabel label2;
	private JScrollPane panel1;
	private JPanel panel2;
	private JPanel panel3;
	private boolean xmlValid;
	private boolean code;
	private InterpretationXML interpretationXML;


	/**
	 * Constructeur
	 */
	public Accueil(){

		this.setTitle("Accueil");
		Container conteneur = this.getContentPane();
		GroupLayout layout = new GroupLayout(conteneur);
		conteneur.setLayout(layout);
		layout.setAutoCreateGaps(true);
		layout.setAutoCreateContainerGaps(true);

		textField = new JTextField("Choisir un fichier XML...");
		textField.setEnabled(false);
		parcourir = new JButton("Parcourir");
		parcourir.addActionListener(this);
		label1 = new JLabel("Contenu du fichier XML : ");
		textArea = new JTextArea(30,60);
		textArea.setEditable(false);
		panel1 = new JScrollPane(textArea);
		
		executer = new JButton("Executer");
		executer.addActionListener(this);
		executer.setEnabled(false);
		genererCode = new JButton("Preparer campagne" +
				"");
		genererCode.addActionListener(this);
		genererCode.setEnabled(false);
		fermer = new JButton("Fermer");
		fermer.addActionListener(this);
		panel2 = new JPanel(new GridBagLayout());
		panel3 = new JPanel(new GridBagLayout());

		GridBagConstraints c = new GridBagConstraints();
		//natural height, maximum width
		c.fill = GridBagConstraints.HORIZONTAL;
		c.weightx = 0.5;
		c.ipady = 20;
		c.gridx = 0;
		c.gridy = 0;
		panel2.add(executer, c);
		c.gridx = 1;
		c.insets = new Insets(0,20,0,0);
		panel2.add(genererCode, c);
		c.gridx = 2;
		c.insets = new Insets(0,20,0,0);
		c.anchor = GridBagConstraints.SOUTH;
		panel2.add(fermer, c);

		c.fill = GridBagConstraints.HORIZONTAL;
		c.insets = new Insets(0,0,0,0);
		c.ipadx = 30;
		c.ipady = 10;
		c.gridx = 0;
		c.gridy = 0;
		panel3.add(textField, c);
		c.weightx = 0;
		c.ipadx = 0;
		c.ipady = 2;
		c.gridx = 1;
		c.insets = new Insets(0,30,0,0);
		panel3.add(parcourir, c);


		layout.setHorizontalGroup(layout.createSequentialGroup()
				.addGroup(layout.createParallelGroup(LEADING)
						.addGroup(layout.createSequentialGroup()
								.addComponent(panel3))
								.addGroup(layout.createParallelGroup(LEADING)
										.addComponent(label1)
										.addComponent(panel1))
										.addGroup(layout.createSequentialGroup()
												.addComponent(panel2))
						)		
				);

		layout.setVerticalGroup(layout.createSequentialGroup()
				.addGap(50)
				.addGroup(layout.createParallelGroup(BASELINE)
						.addComponent(panel3))
						.addGap(30)
						.addGroup(layout.createSequentialGroup()
								.addComponent(label1)
								.addComponent(panel1))
								.addGap(30)
								.addGroup(layout.createParallelGroup(BASELINE)	 
										.addComponent(panel2))
				);

		xmlValid = false;
		code = false;
		this.pack();

		//tuer le processus en cliquant sur la croix pour fermer la fenetre
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setResizable(false);
		this.setVisible(true);

		//centrer la fenetre 
		Dimension screen = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
		this.setLocation((screen.width - this.getSize().width)/2, 0);
	}


	public static void main(String args[]){

		new Accueil();
	}

	public void actionPerformed(ActionEvent e) {

		Object selected = e.getSource();

		if(selected == parcourir)
		{
			FileFilter filtre = new FiltreXML("Fichier de type XML (*.xml)", ".xml");
			JFileChooser fileChooser = new JFileChooser();
			fileChooser.setFileFilter(filtre);
			fileChooser.showOpenDialog(this);
			String filePath = fileChooser.getSelectedFile().getAbsolutePath();
			SAXParseException ex = null;

			interpretationXML = new InterpretationXML(filePath);

			if(filePath != null)
			{
				textField.setEnabled(true);
				textField.setText(filePath);
				try {
					if(xmlValid = interpretationXML.isValid())
					textArea.setText(new ExtendedFile(filePath).toString());


				} catch (SAXParseException e1) {
					ex = e1;
					
				} catch (IOException e1) {
				} catch (SAXException e1) {
				}

				//On verifie le fichier xml choisi
				if (xmlValid){
					genererCode.setEnabled(true);
				}
				else{
//					JOptionPane.showMessageDialog(this, "Le fichier XML selectionné n'est pas conforme au schéma attendu");
					//JOptionPane.showMessageDialog(this, "Error line " + ex.getLineNumber() + " :  " + ex.getMessage());
					textArea.append( "Error line " + ex.getLineNumber() + " :  " + ex.getMessage() + "\n");
				}
			}
		}else if(selected == executer){
			if(code){
				ProgressionTests progressionTests;
				try {

					progressionTests = new ProgressionTests();
					progressionTests.setVisible(true);
					this.setVisible(false);
					progressionTests.getProgression().setMinimum(0);
					progressionTests.getProgression()
					.setMaximum(interpretationXML.getCamp()
							.getCampagne().size());
					System.out.println(interpretationXML.getCamp().getCampagne().size() + "rrrrr");


					ExecutionCode exe = new ExecutionCode(interpretationXML.getCamp().getCampagne(),progressionTests);
					exe.executerCampagne();


				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
			}


		}else if(selected == genererCode){
			JOptionPane.showMessageDialog(this, "Campagne prête");            
			executer.setEnabled(true);
			code = true;
			interpretationXML.preparerCampagne();
			interpretationXML.genererCode();


		}else if(selected == fermer){
			System.exit(0);
		}

	}



}